package com.dgut.lab.security.filter;

import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DgutOAuth2RedirectFilter extends OncePerRequestFilter {
    private static final String APPID = "javaee";
    private static final String DEFAULT_AUTHORIZATION_REQUEST_BASE_URI = "/oauth2/dgut";
    private static final String AUTHENTICATION_URL = "https://cas.dgut.edu.cn?appid={APPID}";

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 如果不是/oauth2/dgut请求，则继续下一个过滤器。
        if (!request.getRequestURI().endsWith(DEFAULT_AUTHORIZATION_REQUEST_BASE_URI)) {
            filterChain.doFilter(request, response);
            return;// 执行完安全过滤器链后不执行后面的代码。
        }
//        System.out.println("执行redirect");
        String uriString = UriComponentsBuilder.fromUriString(AUTHENTICATION_URL)
                .encode()
                .buildAndExpand(APPID).toUriString();
        response.sendRedirect(uriString);
    }
}
